package com.project.frba.bifront.client.view.descriptors;

import com.google.gwt.user.client.ui.Composite;
import com.gwtext.client.core.Connection;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.data.XmlReader;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.Form;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.form.event.FormListenerAdapter;
import com.gwtext.client.widgets.layout.FitLayout;
import com.project.frba.bifront.client.view.MessageWindow;

public class UploadDescriptorForm extends Composite {

	private Window mainWindow = new Window("Descriptor");
	
	private DescriptorList parent;

	public UploadDescriptorForm(DescriptorList descriptorList) {
		this.parent = descriptorList;
		final FormPanel formPanel = new FormPanel();
		formPanel.setFileUpload(true);

		final TextField file = new TextField("File", "file");
		file.setInputType("file");
		formPanel.add(file);

		formPanel.addButton(new Button("Upload", new ButtonListenerAdapter() {
			public void onClick(Button button, EventObject e) {
				formPanel.getForm().submit("./uploadServer", null, Connection.POST, "Cargando...", false);
			}
		}));

		final XmlReader reader = new XmlReader("data", new RecordDef(new FieldDef[] { new StringFieldDef("responseMsg", "responseMsg") }));
		reader.setSuccess("@success");

		final XmlReader errorReader = new XmlReader("data", new RecordDef( new FieldDef[] { new StringFieldDef("responseMsg") }));
		errorReader.setSuccess("@success");
		
		formPanel.setReader(reader);
		formPanel.setErrorReader(errorReader);

		formPanel.addFormListener(new FormListenerAdapter() {
			public void onActionComplete(Form form, int httpStatus,	String responseText) {
				new MessageWindow("Se ha cargado correctamente el archivo.");
				parent.reload();
				mainWindow.close();
			}
			
			public void onActionFailed(Form form, int httpStatus,  String responseText) {
				new MessageWindow("No se ha podido cargar el archivo.");
				
			}
		});

		mainWindow.setWidth(450);
		mainWindow.setHeight(120);
		mainWindow.setLayout(new FitLayout());
		mainWindow.add(formPanel);
		initWidget(mainWindow);
		mainWindow.show();
	}

}
